package com.example.front.service.impl;

import com.example.front.service.ICartService;
import com.example.gok_mall.constUtil.ConstUtil;
import com.example.front.dao.CartDao;
import com.example.front.dao.ProductDao;
import com.example.gok_mall.entity.Cart;
import com.example.gok_mall.entity.Product;
import com.example.gok_mall.reponseData.ResponseCode;
import com.example.gok_mall.reponseData.ResultData;
import com.example.gok_mall.util.BigDecimalUtil;
import com.example.front.vo.CartProductVo;
import com.example.front.vo.CartVo;
import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.apache.commons.collections.CollectionUtils;

import java.math.BigDecimal;
import java.util.List;

@Service
public class CartServiceImpl implements ICartService {

    @Autowired
    private CartDao cartDao;

    @Autowired
    private ProductDao productDao;

    //查询购物车中商品
    @Override
    public ResultData<CartVo> list(Integer userId) {
        CartVo cartVo = this.getCartVoLimit(userId);
        return ResultData.createData(cartVo);
    }

    //购物车全选或全不选
    @Override
    public ResultData<CartVo> selectOrUnselectAll(Integer userId,Integer checked,Integer productId){
        cartDao.checkedOrUncheckedProduct(userId,checked,productId);
        return this.list(userId);
    }

    //获取用户购物车中商品数量
    @Override
    public  ResultData<Integer> getCartProductCount(Integer userId){
        if(userId == null){
            return ResultData.createData(0);
        }
        return ResultData.createData(cartDao.selectProductCountByUserId(userId));
    }


    //添加商品到购物车
    @Override
    public ResultData<CartVo> add(Integer userId, Integer productId, Integer count) {

        if (productId == null || count == null) {
            return ResultData.fail(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMage());
        }
        Cart cart = cartDao.selectCatByUserIdProductId(userId, productId);

        if (cart == null) {
            //产品不再购物车里,需要新增购物车记录
            Cart cartItem = new Cart();
            cartItem.setQuantity(count);
            cartItem.setChecked(ConstUtil.Cart.CHECKED);
            cartItem.setProductId(productId);
            cartItem.setUserId(userId);
            cartDao.insert(cartItem);
        } else {
            //产品已经在购物车
            //如果产品已存在购物车，则数量相加
            count = cart.getQuantity() + count;
            cart.setQuantity(count);
            cartDao.updateByPrimaryKeySelective(cart);
        }
        return this.list(userId);
    }


    //更新商品到购物车
    @Override
    public ResultData<CartVo> update(Integer userId, Integer productId, Integer count) {

        if (productId == null || count == null) {
            return ResultData.fail(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMage());
        }
        Cart cart = cartDao.selectCatByUserIdProductId(userId, productId);
        if (cart != null) {
            cart.setQuantity(count);
        }
        cartDao.updateByPrimaryKeySelective(cart);
        return this.list(userId);
    }

    //删除购物车中的商品
    @Override
    public ResultData<CartVo> deleteProduct(Integer userId, String productIds) {
        List<String> productList = Splitter.on(",").splitToList(productIds);
        if (CollectionUtils.isEmpty(productList)) {
            return ResultData.fail(ResponseCode.ILLEGAL_ARGUMENT.getCode(), ResponseCode.ILLEGAL_ARGUMENT.getMage());
        }
        cartDao.deleteByUserIdProductIds(userId, productList);
        return this.list(userId);
    }

    //封装的一个根据用户Id来获取购物车信息的方法
    private CartVo getCartVoLimit(Integer userId) {
        CartVo cartVo = new CartVo();
        List<Cart> cartList = cartDao.selectCartByUserId(userId);

        List<CartProductVo> cartProductVoList = Lists.newArrayList();

        //设置购物车总价
        BigDecimal cartTotalPrice = new BigDecimal("0");

        if (CollectionUtils.isNotEmpty(cartList)) {
            for (Cart cartItem : cartList) {
                CartProductVo cartProductVo = new CartProductVo();
                cartProductVo.setId(cartItem.getId());
                cartProductVo.setUserId(userId);
                cartProductVo.setProductId(cartItem.getProductId());

                Product product = productDao.selectByPrimaryKey(cartItem.getProductId());

                if (product != null) {
                    cartProductVo.setProductMainImage(product.getMainImage());
                    cartProductVo.setProductName(product.getName());
                    cartProductVo.setProductSubtitle(product.getSubtitle());
                    cartProductVo.setProductStatus(product.getStatus());
                    cartProductVo.setProductPrice(product.getPrice());

                    cartProductVo.setProductStock(product.getStock());

                    //判断库存

                    int buyLimitCount ;
                    buyLimitCount=0;
                    if(product.getStock() !=null&&cartItem.getQuantity() != null){
                        if (product.getStock()>=cartItem.getQuantity()) {
                            //库存充足的时候
                            buyLimitCount = cartItem.getQuantity();
                            cartProductVo.setLimitQuantity(ConstUtil.Cart.LIMIT_MUM_SUCCESS);
                        } else {
                            //库存的不足的时候
                            buyLimitCount = product.getStock();
                            cartProductVo.setLimitQuantity(ConstUtil.Cart.LIMIT_MUM_FAIL);
                            //购物车中更新有效库存

                            Cart cartForQuantity = new Cart();
                            cartForQuantity.setId(cartItem.getId());
                            cartForQuantity.setQuantity(buyLimitCount);
                            cartDao.updateByPrimaryKeySelective(cartForQuantity);
                        }
                    }
                    cartProductVo.setQuantity(buyLimitCount);

                    //计算总价
                    cartProductVo.setProductTotalPrice(BigDecimalUtil.mul(product.getPrice().doubleValue(), cartProductVo.getQuantity()));
                    cartProductVo.setProductChecked(cartItem.getChecked());
                }

                if (cartItem.getChecked() == ConstUtil.Cart.CHECKED) {
                    //如果已经勾选，增加到整个购物车总价中
                    cartTotalPrice = BigDecimalUtil.add(cartTotalPrice.doubleValue(), cartProductVo.getProductTotalPrice().doubleValue());
                }
                cartProductVoList.add(cartProductVo);
            }
        }

        cartVo.setCartTotalPrice(cartTotalPrice);
        cartVo.setCartProductVoList(cartProductVoList);
        cartVo.setAllChecked(this.getAllCheckedStatus(userId));
        //cartVo.setImageHost(PropertiesUtil.getProperty("ftp.server.http.prefix"));

        return cartVo;
    }


    //封装的购物车中商品的是否选中状态
    private boolean getAllCheckedStatus(Integer userId) {
        if (userId == null) {
            return false;
        }
        return cartDao.selectCartProductCheckedStatusByUserId(userId) == 0;
    }

}
